import type { Position, PositionType } from './types'

// 通过legend显示位置，获取legend位置信息数据
export function getLegendPos(position: PositionType) {
  const offset = 1
  const map: Record<PositionType, Position> = {
    tl: { left: offset, top: 0 },
    tc: { left: 'center', top: 0 },
    tr: { right: offset, top: 0 },
    bl: { left: offset, bottom: 0 },
    bc: { left: 'center', bottom: 0 },
    br: { right: offset, bottom: 0 }
  }
  return map[position]
}

// 16进制颜色转rgb
export function hexColorToRgb(hexColor: string) {
  const reg = /^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/gi
  const radix = 16
  const match = reg.exec(hexColor)
  if (!match) {
    return { r: 0, g: 0, b: 0 }
  }
  return {
    r: parseInt(match[1], radix),
    g: parseInt(match[2], radix),
    b: parseInt(match[3], radix)
  }
}

export function decodePolygon(
  coordinate: any,
  encodeOffsets: any,
  encodeScale: any
) {
  const result = [] as any
  let prevX = encodeOffsets[0]
  let prevY = encodeOffsets[1]
  for (let i = 0; i < coordinate.length; i += 2) {
    let x = coordinate.charCodeAt(i) - 64
    let y = coordinate.charCodeAt(i + 1) - 64
    // ZigZag decoding
    x = (x >> 1) ^ -(x & 1)
    y = (y >> 1) ^ -(y & 1)
    // Delta deocding
    x += prevX
    y += prevY
    prevX = x
    prevY = y
    // Dequantize
    result.push([x / encodeScale, y / encodeScale])
  }
  return result
}

export const decode = (json: any) => {
  if (!json.UTF8Encoding) {
    return json
  }
  let encodeScale = json.UTF8Scale
  if (encodeScale == null) {
    encodeScale = 1024
  }
  const features = json.features
  for (let f = 0; f < features.length; f++) {
    const feature = features[f]
    const geometry = feature.geometry
    const coordinates = geometry.coordinates
    const encodeOffsets = geometry.encodeOffsets
    for (let c = 0; c < coordinates.length; c++) {
      const coordinate = coordinates[c]
      if (geometry.type === 'Polygon') {
        coordinates[c] = decodePolygon(
          coordinate,
          encodeOffsets[c],
          encodeScale
        )
      } else if (geometry.type === 'MultiPolygon') {
        for (let c2 = 0; c2 < coordinate.length; c2++) {
          const polygon = coordinate[c2]
          coordinate[c2] = decodePolygon(
            polygon,
            encodeOffsets[c][c2],
            encodeScale
          )
        }
      }
    }
  }
  // Has been decoded
  json.UTF8Encoding = false
  return json
}
